<template>
  <div class="designer-page" v-if="designerInfo">
    <Scroll class="page-scroll" :data="designerInfo" ref="pageScroll">
      <my-home-page-cmp @worksDetail="handleWorksDetail" :designerInfo="designerInfo"></my-home-page-cmp>
    </Scroll>
    <div class="btn-wrapper" v-if="userInfo ? !parseInt(userInfo.identity_type) : true">
      <div class="contact" @click="contactClick" style="display: none">
        <my-button name="联系设计师" :showBg="false" />
        <a :href="'tel:'+ dPhone" v-if="dPhone"></a>
      </div>
      <div class="appointment">
        <my-button name="立即预约" @btnClick="appointmentClick" />
      </div>
    </div>
    <Tip title="预约" class="appointment" ref="appointment">
      <div class="input-box">
        <van-form @submit="onSubmit">
          <van-field required label="您的称呼" v-model="form.name" placeholder="请输入您的姓名" />
          <van-field
            required
            label="您的手机"
            :rules="[{ validator, message: '请输入有效手机号码' }]"
            type="tel"
            v-model="form.phone"
            placeholder="请输入您的手机号"
          />
          <van-field
            type="number"
            required
            :rules="[{ pattern, message: '请输入有效验证码' }]"
            v-model="form.captcha"
            label="验证码"
            placeholder="请输入验证码"
          >
            <template slot="extra">
              <span @click="getCodeClick" v-if="showGetCode">{{ codeTxt }}</span>
              <span v-else style="position:relative; left: -0.4rem">{{time}}s</span>
            </template>
          </van-field>
          <van-field
            rows="3"
            v-model="form.message"
            autosize
            label="您的留言"
            type="textarea"
            placeholder="请输入您的留言"
            maxlength="50"
            show-word-limit
          />
        </van-form>
      </div>
      <my-button name="确定" @btnClick="onSubmit" />
    </Tip>
    <transition name="slide">
      <router-view></router-view>
    </transition>
  </div>
</template>
<script>
import Scroll from '@/components/scroll/scroll'
import Tip from '@/components/tip/tip'
import MyHomePageCmp from '@/components/my-homepage-cmp/my-homepage-cmp'
import { getDesignerDetail, appointmentDesigner } from '@/api/home'
import { getCaptcha } from '@/api/my'
import wx from 'weixin-js-sdk'
const constantTime = 60
const ERR_OK = 200
export default {
  components: {
    Scroll,
    Tip,
    MyHomePageCmp
  },
  data () {
    return {
      showGetCode: true,
      time: constantTime,
      timer: null,
      codeTxt: '获取验证码',
      phone: 18888430435,
      message: '',
      designerInfo: null,
      form: {
        designerId: '',
        phone: '',
        name: '',
        captcha: '',
        message: ''
      },
      pattern: /^[0-9]*$/,
      dPhone: '',
      userInfo: null
    }
  },
  watch: {
    time (newVal) {
      if (newVal <= 0) {
        this.timer && clearInterval(this.timer)
        this.showGetCode = true
        this.codeTxt = '重新获取'
        this.time = constantTime
      }
    }
  },
  created () {
    if (localStorage.getItem('USER')) {
      this.userInfo = JSON.parse(localStorage.getItem('USER'))
    }
    if (window.location.hash.includes('id=') && window.location.hash.includes('type=share')) {
      const id = window.location.hash.split('id=')[1].split('&type=')[0]
      const type = window.location.hash.split('id=')[1].split('&type=')[1]
      const obj = Object.assign({}, { id, type })
      localStorage.setItem('GET_SHARE_INTEGRAL', JSON.stringify(obj))
    }
    if (this.$route.query.id) {
      this._getDesignerDetail(this.$route.query.id).then(() => {
        if (this.designerInfo.phone && !this.designerInfo.company_tel) {
          this.dPhone = this.designerInfo.phone
        } else if (this.designerInfo.company_tel && !this.designerInfo.phone) {
          this.dPhone = this.designerInfo.company_tel
        } else if (this.designerInfo.phone && this.designerInfo.company_tel) {
          this.dPhone = this.designerInfo.phone
        }
      })
    } else {
      this.$router.back()
    }
  },
  destroyed () {
    this.timer && clearInterval(this.timer)
  },
  methods: {
    contactClick () {
      if (!this.dPhone) {
        this.$toast('该设计师暂时没有联系方式')
      }
    },
    validator (val) {
      return /^[1][3,4,5,7,8,9][0-9]{9}$/.test(val)
    },
    onSubmit () {
      this.form.designerId = this.$route.query.id
      this._appointmentDesigner(this.form).then(res => {
        if (res.code === ERR_OK) {
          this.$refs.appointment.hide()
          this.$toast('预约成功~')
        }
      })
    },
    handleWorksDetail (item) {
      if (this.$route.path === '/home/designer-detail') {
        if (item.link) {
          wx.miniProgram.getEnv(ress => {
            if (ress.miniprogram) {
              wx.miniProgram.navigateTo({
                url: `/pages/index/index?return_url=${item.link}`
              })
            }
          })
          return
        }
        this.$router.push({
          path: '/home/designer-detail/case-detail',
          query: { id: this.$route.query.id, case_id: item.id }
        })
      } else if (this.$route.path === '/designer/home-page') {
        if (item.link) {
          wx.miniProgram.getEnv(ress => {
            if (ress.miniprogram) {
              wx.miniProgram.navigateTo({
                url: `/pages/index/index?return_url=${item.link}`
              })
            }
          })
          return
        }
        this.$router.push({
          path: '/designer/home-page/case-detail',
          query: { id: this.$route.query.id, case_id: item.id }
        })
      }
    },
    appointmentClick () {
      const me = this
      if (this.$store.getters.userInfo) {
        this.$refs.appointment.show()
      } else {
        this.$toast({
          message: '暂未登陆~',
          duration: 1000,
          onClose: function () {
            me.$router.push('/login')
          }
        })
      }
    },
    getCodeClick () {
      if (this.showGetCode) {
        if (!this.form.phone) {
          this.$toast('手机号码不能为空')
          return
        }
        this._getCaptcha(this.form.phone).then(() => {
          this.showGetCode = false
          this.timer = setInterval(() => {
            this.time -= 1
          }, 1000)
        })
      }
    },
    _getDesignerDetail (id) {
      return getDesignerDetail(id)
        .then(res => {
          if (res.code === ERR_OK) {
            this.designerInfo = res.data
            return Promise.resolve()
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    _appointmentDesigner ({ designerId, phone, name, captcha, message }) {
      return appointmentDesigner({ designerId, phone, name, captcha, message })
        .then(res => {
          if (res.code === ERR_OK) {
            return Promise.resolve(res)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    _getCaptcha (phone) {
      return getCaptcha(phone)
        .then(res => {
          if (res.code === ERR_OK) {
            return Promise.resolve(res)
          }
        })
        .catch(err => {
          console.log(err)
        })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/styles/mixin.scss";
.designer-page {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: #f7f7f7;
  z-index: 9;
  touch-action: none;
  .page-scroll {
    width: 100%;
    height: 100%;
  }

  .appointment {
    .input-box {
      margin-top: 1rem;
      .van-cell {
        padding-left: 0;
        padding-right: 0;
        padding: 15px 0;
        &::after {
          left: 0;
        }
        &::before {
          left: -10px;
        }
      }
    }
  }
}
.btn-wrapper {
  font-size: 0;
  width: 100%;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  display: flex;
  background: #f7f7f7;
  justify-content: space-around;
  align-items: center;
  padding: 0.3rem 0.36rem 0.3rem 0.36rem;
  box-sizing: border-box;
  .contact,
  .appointment {
    width: 48%;
  }
  .contact {
    margin-right: 0.1rem;
  }
  .appointment {
    flex: 1;
  }
  .contact {
    position: relative;
    a {
      position: absolute;
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
    }
  }
}
@include slideEnter();
</style>
